package com.huixi.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huixi.common.pojo.SearchItem;
import com.huixi.common.pojo.SearchResult;
import com.huixi.service.SearchService;
import com.huixi.service.mapper.ItemMapper;

@Service
public class SearchServiceImpl implements SearchService {
	
	@Autowired
	private ItemMapper itemMapper;

	@Override
	public SearchResult searchResult(String keyword, int page, int rows) throws Exception {
		/*
		  //创建一个SolrQuery对象 SolrQuery query = new SolrQuery(); //设置查询条件
		  query.setQuery(keywords); //设置分页条件 if(page <= 0) page = 1;
		  query.setRows(rows); query.setStart((page - 1) * rows); //设置默认搜索域
		  query.set("df", "item_title"); //开启高亮显示 query.setHighlight(true);
		  query.addHighlightField("item_title");
		  query.setHighlightSimplePre("<em style = \"color:red\">");
		  query.setHighlightSimplePost("</em>"); //调用dao执行查询 SearchResult searchResult
		  = searchDao.searchResult(query);
		 */
		SearchResult searchResult = new SearchResult();
		PageHelper.startPage(page, rows);
		// 执行查询
		if(StringUtils.isBlank(keyword)) {
			searchResult.setItemList(null);
			searchResult.setRecordCount(0);
			searchResult.setTotalPages(0);
			return searchResult;
		}
		List<SearchItem> list = itemMapper.getItemListByKw(keyword);
		// 创建一个返回对象
		// 取分页结果
		PageInfo<SearchItem> pageInfo = new PageInfo<SearchItem>(list);
		long total = pageInfo.getTotal();
		
		/*//计算总页数
		long recordCount = searchResult.getRecordCount();
		int totalPage = (int) (recordCount / rows) ;
		if(recordCount % rows >0 ) totalPage ++ ;
		//添加到返回结果
		searchResult.setTotalPages(totalPage);*/
		
		searchResult.setItemList(list);
		searchResult.setRecordCount(total);
		searchResult.setTotalPages(pageInfo.getPages());
		//返回结果
		return searchResult;
	}

}
